package com.tgu.home_action.service.impl.admin;

import com.tgu.home_action.dao.ClientMapper;
import com.tgu.home_action.pojo.Client;
import com.tgu.home_action.pojo.Page;
import com.tgu.home_action.pojo.ResponseData;
import com.tgu.home_action.pojo.state.ResponseState;
import com.tgu.home_action.service.admin.AdminClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

import java.util.List;

@Service
public class AdminClientServiceImpl implements AdminClientService {
    @Autowired
    private ClientMapper clientMapper;

    /**
     * 查询第三方应用
     */
    @Override
    public ResponseData<Page<Client>> getClients(Client client) {
        int sum = clientMapper.getAccordClientsNum(client);
        if (client.getPageNo() == null || client.getPageSize() == null) {
            client.setPageNo(1);
            client.setPageSize(sum);
        }
        client.setStartSize((client.getPageNo() - 1) * client.getPageSize());
        List<Client> clients = clientMapper.getAccordClients(client);
        int pageNum;
        if (client.getPageSize() == 0) {
            pageNum = 0;
        } else {
            pageNum = sum / client.getPageSize();
            if (sum % client.getPageSize() > 0) {
                pageNum++;
            }
        }
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), new Page<>(client.getPageNo(), client.getPageSize(), pageNum, sum, clients));

    }

    /**
     * 添加第三方应用
     */
    @Override
    public ResponseData<Client> addClient(Client client) throws DuplicateKeyException {
        clientMapper.insertClient(client);
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), client);
    }

    /**
     * 修改第三方应用
     */
    @Override
    public ResponseData<Client> updateClient(Client client) {
        clientMapper.updateClient(client);
        client = clientMapper.getById(client.getId());
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), client);
    }

    /**
     * 删除第三方应用
     */
    @Override
    public ResponseData<Client> delClient(Integer clientId) {
        Boolean isSuccess = clientMapper.deleteClient(clientId);
        if (isSuccess) {
            return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue());
        } else {
            return new ResponseData<>(ResponseState.USER_NOT_EXIST.getMessage(), ResponseState.USER_NOT_EXIST.getValue());
        }
    }

}
